import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store/index.js'
import { h } from 'vue'
const Layout = () => import('@/views/LayoutShow.vue')
const Home = () => import('@/views/home/homeIndex.vue')
const Category = () => import('@/views/category/categoryIndex.vue')
const CategorySub = () => import('@/views/category/categorySub.vue')
const Goods = () => import('@/views/goods/goodsIndex.vue')
const Login = () => import('@/views/login/index')
const LoginCallback = () => import('@/views/login/callback.vue')
const CartIndex = () => import('@/views/cart/cartIndex.vue')
const checkOut = () => import('@/views/member/pay/checkout.vue')
const payIndex = () => import('@/views/member/pay/payIndex.vue')
const XtxPayResultPage = () => import('@/views/member/pay/payResult.vue')
const MemberLayout = () => import('@/views/member/peasonLayout.vue')
const MemberHome = () => import('@/views/member/home/HomeIndex.vue')
const OrderIndex = () => import('@/views/member/order/orderIndex.vue')
const MemberDetail = () => import('@/views/member/order/orderDatail.vue')
const routes = [
  {
    path: '/',
    component: Layout,
    children: [{
      path: '/',
      component: Home
    },
    {
      path: '/category/:id',
      component: Category
    },
    {
      path: '/category/sub/:id',
      component: CategorySub
    },
    {
      path: '/product/:id',
      component: Goods
    },
    { path: '/cart', component: CartIndex },
    { path: '/member/checkout', component: checkOut },
    { path: '/member/pay', component: payIndex },
    { path: '/pay/callback', component: XtxPayResultPage },
    {
      path: '/member',
      component: MemberLayout,
      children: [
        { path: '/member', component: MemberHome },
        // { path: '/member/order', component: OrderIndex },
        // { path: '/member/order/:id', component: MemberDetail }
        // vue3写法
        {
          path: 'order/',
          // vue3.0 需要有嵌套关系才能模糊匹配
          component: { render: () => h(<RouterView />) },
          children: [
            { path: '', component: OrderIndex },
            { path: ':id', component: MemberDetail }
          ]
        }
      ]
    }
    ]
  },
  { path: '/login', component: Login },
  { path: '/login/callback', component: LoginCallback }

]
// vue2.0 new VueRouter()
const router = createRouter({
  // 使用hash模式
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    return { top: 0 }
  }
})
// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 用户信息
  const { token } = store.state.user.profile
  // 跳转去member开头的地址却没有登录
  if (to.path.startsWith('/member') && !token) {
    next({ path: '/login', query: { redirectUrl: to.fullPath } })
  }
  next()
})
export default router
